import React, { memo, useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { nanoid } from "nanoid";

import {
  getDetailCommentAction,
  setNewCommentAction,
  getDetailNoteAction,
} from "./store/actionCreators";
import { setOtherUserInfoAction } from "@/pages/other-user/store/actionCreators";

import { Drawer, Input, Button, message, Modal } from "antd";
import {
  LeftOutlined,
  EditOutlined,
  HeartOutlined,
  HeartTwoTone,
  MessageOutlined,
  StarOutlined,
  StarTwoTone,
} from "@ant-design/icons";
import {
  DetailWrapper,
  DetailContent,
  DetailTitle,
  DetailBottomCommnet,
  CommentIsNull,
} from "./style";

import Comment from "./comment";

// 网络请求
import {
  addComment,
  likeNote,
  isLikeNote,
  deleteLikeNote,
  isCollectNote,
  collectNote,
  deleteCollectNote,
  isCircusUser,
  addCircusUser,
  cancelCircusUser,
} from "@/services";
// 处理时间的函数
import moment from "moment";
import { formatTime } from "@/utils/time-util";

const { TextArea } = Input;
let circusRef = false;

export default memo(function Detail(props) {
  // 控制drawer是否显示
  const [visible, setVisible] = useState(false);
  // drawer的受控组件
  const [msg, setMsg] = useState();

  // 收藏
  const [isCollect, setIsCollect] = useState(false);
  // 收藏数
  const [collectNum, setCollectNum] = useState(0);

  // 关注
  const [isCircus, setIsCircus] = useState(false);

  const history = useHistory();

  // redux hook
  const dispatch = useDispatch();

  const {
    noteId,
    noteUserId,
    detailNote,
    commentData,
    userInfo,
    otherUserInfo,
  } = useSelector((state) => ({
    otherUserInfo: state.getIn(["otherUser", "otherUserInfo"]),
    noteId: state.getIn(["comment", "noteId"]),
    noteUserId: state.getIn(["comment", "noteUserId"]),
    detailNote: state.getIn(["comment", "detailNote"]),
    commentData: state.getIn(["comment", "commentData"]),
    userInfo: state.getIn(["user", "userInfo"]),
  }));
  useEffect(() => {
    dispatch(getDetailNoteAction(noteId));
    dispatch(getDetailCommentAction(noteId));
  }, [dispatch, noteId]);

  const { picurl, theme, allLove } = detailNote;
  const { avatar, nickName } = otherUserInfo;

  // 点赞
  const [isLike, setIsLike] = useState(false);
  // 点赞数
  const [likeNum, setLikeNum] = useState(() => {
    return allLove;
  });
  // 让收藏的数据与redux中同步
  useEffect(() => {
    setCollectNum(detailNote.allCollection);
  }, [detailNote]);
  // 点赞的方法
  const handleLike = () => {
    setIsLike(!isLike);
    if (isLike) {
      setLikeNum(likeNum - 1);
    } else {
      setLikeNum(likeNum + 1);
    }
  };
  // 收藏的方法
  const hanleCollect = () => {
    setIsCollect(!isCollect);
    if (isCollect) {
      setCollectNum(collectNum - 1);
      message.error({
        content: "取消收藏",
        duration: 1,
        style: {
          marginTop: "80vh",
        },
      });
    } else {
      setCollectNum(collectNum + 1);
      message.success({
        content: "收藏成功",
        duration: 1,
        style: {
          marginTop: "80vh",
        },
      });
    }
  };

  // 判断用户是否存在做过的行为：点赞、收藏、关注
  useEffect(() => {
    isLikeNote(noteId, userInfo.userId).then((res) => {
      if (res.code === 200) {
        // 点过赞了
        setIsLike(true);
      }
    });
    isCollectNote(noteId, userInfo.userId).then((res) => {
      if (res.code === 200) {
        // 已经收藏了
        setIsCollect(true);
      }
    });
    // 方法一：
    /*     isCircusUser(userInfo.userId, noteUserId).then((res) => {
      if (res.code === 200) {
        setIsCircus(true);
        circusRef = true;
      }
    }); */
    // 方法二：
    detailNote.userId &&
      isCircusUser(userInfo.userId, detailNote.userId).then((res) => {
        if (res.code === 200) {
          setIsCircus(true);
          circusRef = true;
        }
      });
  }, [noteId, userInfo, detailNote]);

  // 跳转到首页
  const jumpToHomePage = () => {
    // 跳转出去的时候，判断一下用户是否点过赞
    let data = {
      noteId,
      userId: userInfo.userId,
      toUserId: detailNote.userId,
    };
    if (likeNum > allLove) {
      // 点赞+1
      likeNote(data).then((res) => {
        console.log(res);
      });
    } else if (likeNum < allLove) {
      // 取消了点赞 - 1
      deleteLikeNote(data).then((res) => {
        console.log(res);
      });
    }
    // 判断一下用户是否收藏了该笔记
    if (collectNum > detailNote.allCollection) {
      collectNote(data).then((res) => {
        console.log(res);
      });
    } else if (collectNum < detailNote.allCollection) {
      deleteCollectNote(data).then((res) => {
        console.log(res);
      });
    }
    // 判断一下用户是否取消或者新增了关注
    if (circusRef !== isCircus) {
      if (isCircus) {
        // 关注了
        const data = {
          userId: userInfo.userId,
          toUserId: detailNote.userId,
        };
        addCircusUser(data).then((res) => {
          console.log("新增关注：", res);
        });
      } else {
        const data = {
          userId: userInfo.userId,
          toUserId: detailNote.userId,
        };
        cancelCircusUser(data).then((res) => {
          console.log("取消关注：", res);
        });
      }
    }

    history.go(-1);
  };
  // 评论相关的方法
  const showDrawer = () => {
    setVisible(true);
    setMsg("");
  };
  const onClose = () => {
    setVisible(false);
  };
  const onChange = (e) => {
    setMsg(e.target.value);
  };
  // 提交评论
  const submitComment = () => {
    // 提交评论 思路： 先把数据放到redux中 然后再说上传到服务器的事情
    onClose();
    if (msg !== "") {
      const data = {
        userId: userInfo.userId,
        toUserId: detailNote.userId,
        noteId: noteId,
        comment: msg,
      };

      addComment(data).then((res) => {
        if (res.code === 200) {
          message.success({
            content: "评论成功！",
            duration: 1,
            style: {
              marginTop: "40vh",
            },
          });
          setMsg("");
          // 存入redux中 让数据能马上显示
          let newComment = {
            nickName: userInfo.nickName,
            avatar: userInfo.avatar,
            gmtCreate: moment().format("YYYY-MM-DD"),
            comment: msg,
          };
          dispatch(setNewCommentAction(newComment));
        } else {
          message.error({
            content: "评论失败！",
            duration: 1,
            style: {
              marginTop: "40vh",
            },
          });
        }
      });
    }
  };
  const jumpToThisUser = () => {
    history.push({
      pathname: "/other_user",
    });
    dispatch(setOtherUserInfoAction());
  };

  // 以下是Modal
  const [isModalVisible, setIsModalVisible] = useState(false);

  const showModal = () => {
    if (isCircus) {
      setIsModalVisible(true);
    } else {
      setIsCircus(true);
    }
  };

  const handleOk = () => {
    setIsModalVisible(false);
    setIsCircus(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <DetailWrapper>
      <DetailTitle>
        <div className="title-left">
          <i onClick={jumpToHomePage}>
            <LeftOutlined style={{ fontSize: "18px" }} />
          </i>
          <div
            className="info"
            onClick={(e) => {
              jumpToThisUser();
            }}
          >
            <img src={avatar} className="info-img" alt="" />
            <span className="nickname">{nickName}</span>
          </div>
        </div>
        <div className="title-right" onClick={showModal}>
          {isCircus ? (
            <button className="btn-circus">已关注</button>
          ) : (
            <button className="btn">关注</button>
          )}
        </div>
      </DetailTitle>
      <div className="content">
        <img src={picurl} alt="" />
      </div>
      <DetailContent>
        <div className="title">{theme}</div>
        <div className="detail">{detailNote.detail}</div>
        <div className="content-bottom">
          发表于 {formatTime(detailNote.gmtCreate)}
        </div>
      </DetailContent>
      <DetailBottomCommnet>
        <button className="comment" onClick={showDrawer}>
          <i>
            <EditOutlined />
          </i>{" "}
          说点什么...
        </button>
        <div className="bottom-item">
          <div className="item">
            <i onClick={handleLike}>
              {isLike ? (
                <HeartTwoTone
                  twoToneColor="#d71345"
                  style={{ fontSize: "25px" }}
                />
              ) : (
                <HeartOutlined style={{ fontSize: "25px" }} />
              )}
            </i>
            <span>{likeNum}</span>
          </div>
          <div className="item">
            <i onClick={hanleCollect}>
              {isCollect ? (
                <StarTwoTone
                  twoToneColor="#f58220"
                  style={{ fontSize: "25px" }}
                />
              ) : (
                <StarOutlined style={{ fontSize: "25px" }} />
              )}
            </i>
            <span>{collectNum}</span>
          </div>
          <div className="item">
            <i>
              <MessageOutlined style={{ fontSize: "25px" }} />
            </i>
            <span>{commentData.length}</span>
          </div>
        </div>
      </DetailBottomCommnet>
      <div className="comment-wrap">
        {commentData.length > 1 ? (
          commentData.map((item) => {
            return <Comment data={item} key={nanoid()} />;
          })
        ) : (
          <CommentIsNull>暂时还没有评论~</CommentIsNull>
        )}
      </div>
      <>
        <Drawer
          title="喜欢就给个评论支持一下~"
          placement="bottom"
          onClose={onClose}
          visible={visible}
        >
          <TextArea showCount maxLength={100} onChange={onChange} value={msg} />
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              marginTop: "30px",
            }}
          >
            <Button
              onClick={submitComment}
              type="primary"
              style={{
                backgroundColor: "#45b97c",
              }}
            >
              发表
            </Button>
          </div>
        </Drawer>
      </>
      <Modal
        title="提示"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        cancelText="取消"
        okText="确认"
      >
        确认不再关注？
      </Modal>
    </DetailWrapper>
  );
});
